package com.coldworks.coldjoke.task;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.coldworks.base.manager.BaseNetworkManager;
import com.coldworks.base.manager.BasePrefManager;
import com.coldworks.base.manager.BaseStorageManager;
import com.coldworks.base.util.BaseCONST;
import com.coldworks.coldjoke.R;
import com.coldworks.coldjoke.util.CONST;

/**
 * 检测线程，用以询问服务器是否有更新 若有更新： 如果非强制：通过顶栏通知提示 如果强制： 通知主activity弹窗提示
 * 
 * @since 2012-03-23
 */
public class CheckVersionTask extends AsyncTask<Void, Void, Integer> {
	protected final Logger log = LoggerFactory.getLogger(this.getClass());
	private Context context;
	private int versionCode;

	private boolean isAutoCheck;
	private String apkURL;
	private String updateNotice;

	private ProgressDialog progressDialog;

	public CheckVersionTask(Context context, int versionCode,
			boolean isAutoCheck) {
		this.context = context;
		this.versionCode = versionCode;
		this.isAutoCheck = isAutoCheck;
	}

	@Override
	protected void onPreExecute() {
		if (!this.isAutoCheck) {
			this.progressDialog = new ProgressDialog(context);
			this.progressDialog.setMessage(context.getResources().getString(
					R.string.checking_version));
			this.progressDialog.setIndeterminate(true);
			this.progressDialog.setCancelable(true);
			this.progressDialog.setOnCancelListener(new OnCancelListener() {

				@Override
				public void onCancel(DialogInterface dialog) {
					CheckVersionTask.this.cancel(true);
				}
			});
			this.progressDialog.show();
		}
	}

	@Override
	protected Integer doInBackground(Void... params) {
		long curTime = System.currentTimeMillis();
		long lastTime = BasePrefManager.getInstance().getLongFromPrefs(context,
				BaseCONST.KEY.LAST_NOTIFY_TIME, 0L);
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH:mm:ss");
		log.info("lastTime:" + formatter.format(new Date(lastTime))
				+ " curTime:" + formatter.format(new Date(curTime)));
		if (this.isAutoCheck
				&& (lastTime + (BaseCONST.NOTIFICATION.UPDATE_INTERVAL_DAY * 24 * 60 * 60 * 1000)) > curTime) {
			log.info("nothing");
			return BaseCONST.OP.NO_UPDATE;
		}
		String checkURL = CONST.URL.APP + "?client=android&action=getVersion";
		try {
			String result = BaseNetworkManager.getInstance().httpGET(context,
					checkURL);
			Log.d("result check url", result);
			if (isCancelled()) {
				log.info("cancelled");
				return BaseCONST.OP.CANCEL;
			}
			if (result == null) {
				log.warn("http return null");
				return BaseCONST.OP.NO_UPDATE;
			}
			JSONObject jsonObject = new JSONObject(result);

			if (Integer.valueOf(jsonObject.getString("version")) <= versionCode) {
				log.info("version newest");
				return BaseCONST.OP.NO_UPDATE;
			}

			if (isCancelled()) {
				return BaseCONST.OP.CANCEL;
			}

			// 至此，版本验证通过
			if (jsonObject.getString("update").equals("true")) {
				// 需要提示升级
				if (jsonObject.getString("force_update").equals("true")) {
					// 需要强制升级
					if (this.isAutoCheck) {
						// 且是自动检测
						Log.d("test1", "force and autocheck");
						this.updateNotice = jsonObject
								.getString("update_notice");
						this.apkURL = jsonObject.getString("apk_url");
						return BaseCONST.OP.REQUIRE_UPDATE_FORCE;
					} else {
						// 但不是自动检测
						Log.d("test2", "force but not autocheck");
						BasePrefManager.getInstance().setLongToPrefs(context,
								BaseCONST.KEY.LAST_NOTIFY_TIME, curTime);
						return BaseCONST.OP.NO_UPDATE;
					}
				} else {
					// 不需强制升级
					Log.d("test3", "not force and both check");
					this.updateNotice = jsonObject.getString("update_notice");
					this.apkURL = jsonObject.getString("apk_url");
					BasePrefManager.getInstance().setLongToPrefs(context,
							BaseCONST.KEY.LAST_NOTIFY_TIME, curTime);
					return BaseCONST.OP.REQUIRE_UPDATE;
				}
			} else {
				// 不提示升级
				log.info("found new but not asking");
			}
		} catch (Exception e) {
			log.error("", e);
		}
		return BaseCONST.OP.NO_UPDATE;
	}

	@Override
	protected void onPostExecute(Integer result) {
		if (this.progressDialog != null) {
			this.progressDialog.dismiss();
		}
		switch (result) {
		case BaseCONST.OP.CANCEL:
			log.info("cancelled");
			break;
		case BaseCONST.OP.NO_UPDATE:
			if (!this.isAutoCheck) {
				Toast.makeText(
						context,
						context.getResources().getString(
								R.string.check_version_newest),
						Toast.LENGTH_LONG).show();
			}
			break;
		case BaseCONST.OP.REQUIRE_UPDATE:
			showUpdates();
			break;
		case BaseCONST.OP.REQUIRE_UPDATE_FORCE:
			showForceUpdates();
			break;
		}

	}

	private void showForceUpdates() {
		Builder builder = new AlertDialog.Builder(context);
		builder.setCancelable(false);
		builder.setMessage(this.updateNotice + "\r\n\r\n"
				+ context.getString(R.string.check_version_update_now));
		builder.setNegativeButton(
				context.getResources().getString(R.string.check_version_quit),
				new OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// ((MainActivity) context).quit();
					}
				});
		builder.setPositiveButton(
				context.getResources().getString(R.string.ok),
				new OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						log.info("user say update");

						File tmpDir = BaseStorageManager.getInstance()
								.getTempDir();
						if (tmpDir == null) {
							Toast.makeText(
									context,
									context.getResources().getString(
											R.string.no_sdcard_found),
									Toast.LENGTH_LONG).show();
							return;
						}

						new DownloadApkTask(context, apkURL, tmpDir
								.getAbsolutePath()
								+ File.separator
								+ "androidesk.apk", true, false, true)
								.execute();
					}

				});

		builder.create().show();

	}

	private void showUpdates() {
		Builder builder = new AlertDialog.Builder(context);
		builder.setCancelable(true);
		builder.setMessage(this.updateNotice + "\r\n\r\n"
				+ context.getString(R.string.check_version_update_now));
		builder.setNegativeButton(
				context.getResources().getString(
						R.string.check_version_update_later),
				new OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
					}
				});
		builder.setPositiveButton(
				context.getResources().getString(R.string.ok),
				new OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						log.info("onPostExecute", "user say update");

						try {
							Intent intent = new Intent(Intent.ACTION_VIEW, Uri
									.parse(CONST.LOCAL.MARKET_LINK));
							context.startActivity(intent);
						} catch (Exception e) {

							log.warn("download from official");

							File tmpDir = BaseStorageManager.getInstance()
									.getTempDir();
							if (tmpDir == null) {
								Toast.makeText(
										context,
										context.getResources().getString(
												R.string.no_sdcard_found),
										Toast.LENGTH_LONG).show();
								return;
							}

							new DownloadApkTask(context, apkURL, tmpDir
									.getAbsolutePath()
									+ File.separator
									+ "coldjoke.apk", true, false, true)
									.execute();
						}
					}

				});

		builder.create().show();

	}
}